package com.rigsofrods.truckeditor.rig.parser;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.tree.TreeModel;

import com.rigsofrods.truckeditor.rig.TruckFileModel;


public class TruckFileWriter {
	private static FileWriter fw;
	
	public static void writeToFile(TruckFileModel truck, File f) throws IOException {
		if(f.exists()){
			File copy = File.createTempFile("backup_", null, f.getParentFile());
			copy.deleteOnExit();
			createBackupCopy(f, copy);
			f.delete();
		}
		f.createNewFile();
		fw = new FileWriter(f);
		TreeModel model = truck;
		if (model != null) {
			Object root = model.getRoot();
			fw.write(root.toString());
			System.out.println(root.toString());
			walk(model, root);
		} else
			System.out.println("Tree is empty.");
	}

	protected static void walk(TreeModel model, Object o) throws IOException {
		int cc;
		cc = model.getChildCount(o);
		for (int i = 0; i < cc; i++) {
			Object child = model.getChild(o, i);
			if (model.isLeaf(child)){
				//System.out.println(child.toString());
				fw.write(child.toString());
				fw.write(Character.LINE_SEPARATOR);
			}else{
				System.out.print(child.toString() + "--");
				fw.write(child.toString());
				fw.write(Character.LINE_SEPARATOR);
				walk(model, child);
			}
		}
	}
	
	private static void createBackupCopy(File orig, File copy) throws IOException {
		FileReader inputStream = null;
        FileWriter outputStream = null;

        try {
            inputStream = new FileReader(orig);
            outputStream = new FileWriter(copy);

            int c;
            while ((c = inputStream.read()) != -1) {
                outputStream.write(c);
            }
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
	}
}
